import JSONP from "jsonp";
import axios from "axios";
import { Modal } from "antd";
import Utils from "../utils/utils"
export default class Axios {
  static requestList(_this,url, params,isMOke) {
    var data = {
      params: params,
      isMOke
    };
    this.ajax({
      url,
      data
    }).then(data => {
      if (data && data.result) {
        _this.setState({
          list: data.result.item_list.map((item, index) => {
            item.key = index;
            return item;
          }),
          pagination: Utils.pagination(data, current => {
            _this.params.page = current;
            _this.requestList(); 
          })
        });
      }
    });
  }

  static jsonp(options) {
    // Promise回调函数用法,resolve回调成功,reject回调失败
    // return new Promise 就可以用.then 链式调用 ES6语法
    return new Promise((resolve, reject) => {
      // jsonp 用法
      JSONP(
        options.url,
        {
          param: "callback"
        },
        function(err, response) {
          // debugger;
          if (response.status == "success") {
            resolve(response);
          } else {
            reject(response.message);
          }
        }
      );
    });
  }

  //封装 ajax
  static ajax(options) {
    let baseApi =""
    if(options.isMoke){
      //如果是ture 用 moke假数据
       baseApi ="https://www.easy-mock.com/mock/5a7278e28d0c633b9c4adbd7/api";
    }else{
      //如果false , 用实际地址
       baseApi ="https://www.easy-mock.com/mock/5a7278e28d0c633b9c4adbd7/api";
    }
    return new Promise((resolve, reject) => {
      axios({
        url: options.url,
        method: "get",
        baseURL: baseApi,
        timeout: 5000,
        params: (options.data && options.data.params) || ""
      }).then(response => {
        if (response.status == "200") {
          //code是后端自己设置的
          if (response.data.code == "0") {
            resolve(response.data);
          } else {
            Modal.info({
              title: "错误提示",
              content: response.data.msg
            });
          }
        } else {
          reject(response.data);
        }
      });
    });
  }
}
